<template>
  <div>
    <van-form @submit="onSubmit">
      <div class="card" v-for="(item, index) in orderList" :key="index">
        <div class="title">
          <span>{{ item.name }}</span>
          <van-icon :name="item.expand ? 'arrow-up' : 'arrow-down'" @click="$set(item, 'expand', !item.expand)" />
        </div>
        <van-cell-group v-show="item.expand">
          <template class="order-item" v-for="(obj, i) in item.properties">
            <!-- 单行文本 -->
            <van-field
              v-if="obj.type === 0 && obj.code !== 'productName'"
              v-model="form[obj.code]"
              :label="obj.name"
              :placeholder="detail ? '' : obj.expound || '请输入'"
              :readonly="detail"
              :rules="obj.required ? [{ required: true }] : []"
              :required="!!obj.required"
            />
            <van-field
              v-if="obj.type === 0 && obj.code === 'productName'"
              v-model="form[obj.code]"
              :label="obj.name"
              :placeholder="detail ? '' : obj.expound || '请关联商品'"
              readonly
              :rules="obj.required ? [{ required: true }] : []"
              @click="showProduct"
              :required="!!obj.required"
            />
            <!-- 多行文本 -->
            <van-field
              v-if="obj.type === 1"
              v-model="form[obj.code]"
              :label="obj.name"
              :placeholder="detail ? '' : obj.expound || '请输入'"
              :readonly="detail"
              :rules="obj.required ? [{ required: true }] : []"
              type="textarea"
              :required="!!obj.required"
            />
            <!-- 选项 -->
            <template v-if="obj.type === 2">
              <!-- 多选 -->
              <van-field
                v-if="obj.multipleChoice === 1"
                :value="form[obj.code] && form[obj.code] + ''"
                :label="obj.name"
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
                @click="
                  showSelectPicker = true
                  selectObj = obj
                "
                :readonly="detail"
                :placeholder="detail ? '' : obj.expound || '请选择'"
              ></van-field>
              <!-- 单选 -->
              <van-field
                v-if="obj.multipleChoice === 0"
                :value="form[obj.code]"
                :label="obj.name"
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
                :readonly="detail"
                :placeholder="detail ? '' : obj.expound || '请选择'"
              >
                <template #input v-if="obj.value">
                  <van-dropdown-menu active-color="#07c060">
                    <van-dropdown-item
                      v-model="form[obj.code]"
                      :title="form[obj.code] || (detail ? '' : obj.expound || '请选择')"
                      :options="obj.value.split(',').map((e) => ({ text: e, value: e }))"
                    />
                  </van-dropdown-menu>
                </template>
              </van-field>
            </template>
            <!-- 日期时间 -->
            <template v-if="obj.type === 3">
              <van-field
                v-model="form[obj.code]"
                :label="obj.name"
                :placeholder="detail ? '' : obj.expound || '请选择时间'"
                :readonly="detail"
                @click="
                  dataObj = obj
                  dateShow = true
                "
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
              />
            </template>
            <!-- 选择部门 -->
            <template v-if="obj.type === 4">
              <van-field
                clickable
                v-model="form[obj.id]"
                :label="obj.name"
                :placeholder="detail ? '' : '请选择部门'"
                :readonly="detail"
                @click="
                  deptObj = obj
                  showDepte = true
                "
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
              />
            </template>
            <!-- 选择员工 -->
            <template v-if="obj.type === 5">
              <van-field
                clickable
                v-model="form[obj.id]"
                :label="obj.name"
                :placeholder="detail ? '' : '请选择员工'"
                :readonly="detail"
                @click="clickUser(obj)"
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
              />
            </template>
            <!-- 数字 -->
            <template v-if="obj.type === 6">
              <van-field
                v-model="form[obj.code]"
                type="number"
                :label="obj.name"
                :rules="obj.required ? [{ required: true }] : []"
                :required="!!obj.required"
                @blur="obj.money && (form[obj.code] = form[obj.code] && (+form[obj.code]).toFixed(2))"
                :readonly="detail || obj.code === 'productUnitPrice'"
                :placeholder="detail ? '' : obj.expound || '请输入'"
              ></van-field>
            </template>
            <!-- 附件 -->
            <template v-if="obj.type === 7">
              <van-field :label="obj.name" :readonly="detail" :required="!!obj.required">
                <template #input>
                  <!-- 商品图片 -->
                  <template v-if="obj.code === 'productUrl'">
                    <div v-if="form[obj.code]">
                      <van-image
                        width="80"
                        height="80"
                        fit="cover"
                        v-for="(unit, unique) in dealDetailUrl(form[obj.code])"
                        :src="unit"
                        :key="unique"
                      />
                    </div>

                    <div v-else class="product-url">关联商品后显示</div>
                  </template>

                  <!-- 上传文件 -->
                  <template v-else>
                    <Upload
                      v-if="obj.more"
                      ref="upload"
                      :format="format"
                      :fileList.sync="form[obj.code]"
                      :multiple="true"
                      :isOnlyShowFile="detail"
                    ></Upload>
                    <Upload
                      v-else-if="!obj.more"
                      ref="upload"
                      :format="format"
                      :fileUrl.sync="form[obj.code]"
                      :multiple="false"
                      :isOnlyShowFile="detail"
                    ></Upload>
                  </template>
                </template>
              </van-field>
            </template>
          </template>
        </van-cell-group>
      </div>
      <div class="cancat-btn">
        <van-button block round @click="cancelBack" native-type="button" key="0">
          取消
        </van-button>
        <van-button v-if="detail" type="info" block round @click="detail = false" native-type="button" key="1">
          编辑
        </van-button>
        <van-button v-if="!detail" block round @click="form.status = '0'" native-type="submit" key="2">
          保存
        </van-button>
        <van-button v-if="!detail" type="info" block round @click="form.status = '1'" native-type="submit" key="3">
          确定
        </van-button>
      </div>
    </van-form>

    <van-popup v-model="dateShow" position="bottom" round>
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="请选择时间"
        @confirm="confirmDate"
        @cancel="dateShow = false"
      />
    </van-popup>

    <!-- 多选 -->
    <van-popup v-model="showSelectPicker" closeable position="bottom" style="min-height: 30%;padding:40px 10px 20px ;">
      <van-checkbox-group v-model="form[selectObj.code]" direction="horizontal">
        <template v-if="selectObj.value">
          <van-checkbox
            :name="item"
            shape="square"
            :readonly="detail"
            v-for="(item, index) in selectObj.value.split(',')"
            :key="index"
          >
            {{ item }}
          </van-checkbox>
        </template>
      </van-checkbox-group>

      <!-- <van-button round block type="info" @click="showSelectPicker = false" style="margin:20px auto 0;">
        确定
      </van-button> -->
      <!-- <template v-if="selectObj.multipleChoice === 0">
        <van-radio-group v-model="form[selectObj.code]">
          <template v-if="selectObj.value">
            <van-radio
              :name="item"
              v-for="(item, index) in selectObj.value.split(',')"
              :key="index"
              :readonly="detail"
              @click="radioClick(item, selectObj.code)"
            >
              {{ item }}
            </van-radio>
          </template>
        </van-radio-group>
      </template> -->
      <!-- <template v-else-if="selectObj.multipleChoice === 1">
      </template> -->
    </van-popup>

    <!-- 选择部门 弹框-->
    <van-popup v-model="showDepte" position="bottom">
      <van-cascader
        v-model="form[deptObj.code]"
        title="选择部门"
        :options="options"
        @close="showDepte = false"
        @finish="selectDept"
        :field-names="{ text: 'deptName', value: 'deptId' }"
      />
    </van-popup>

    <!-- 选择员工 弹框-->
    <van-popup v-model="showPicker" position="bottom" style="min-height: 60%;padding: 20px;" v-if="showPicker">
      <van-radio-group v-model="form[userObj.code]">
        <van-radio
          :name="item.userId"
          v-for="(item, index) in userList"
          :key="index"
          @click="
            form[userObj.id] = item.userName
            showPicker = false
          "
        >
          {{ item.userName }}
        </van-radio>
      </van-radio-group>
    </van-popup>

    <!-- 选择商品弹框 -->
    <van-popup v-if="productShow" v-model="productShow" position="bottom" style="height: 80%">
      <div class="product-title">
        <span style="color:#07c060" @click="productShow = false">关闭</span>
        <span class="title">选择商品</span>
        <span style="color:#07c060" @click="productSubmit">确定</span>
      </div>
      <PullRefreshScrollLoadList :request="getProductList">
        <template v-slot="list">
          <div
            class="product-item"
            :class="selectProduct.id == item.id ? 'active' : ''"
            v-for="(item, i) in list"
            :key="i"
            @click="selectProduct = item"
          >
            <van-image width="40" height="40" :src="item.picture" />
            <div class="content">
              <div class="describe">{{ item.describe }}</div>
              <div class="price">￥{{ item.price }}</div>
            </div>
          </div>
        </template>
      </PullRefreshScrollLoadList>
    </van-popup>
  </div>
</template>

<script>
import { dateFormat } from '@/utils'
import Upload from '@/components/Upload.vue'
import { getAllOrder, getOrderDetail, getOrderEdit, getOrderAdd, getProductList } from '@/api/portrait'
import { getDeptList, getUserList } from '@/api/common'
export default {
  components: { Upload },
  data() {
    return {
      detailList: [],
      id: 0,
      orderList: [],
      detail: false,
      form: {},
      showPicker: false,
      dateShow: false,
      currentDate: new Date(),
      options: [],
      showDepte: false,
      userList: [],
      format: ['png', 'jpg', 'jpeg', 'doc', 'docx', 'pdf', 'xls', 'xlsx'],
      productShow: false, // 商品弹框的显示与隐藏
      productList: [],
      selectProduct: {},
      dataObj: {}, // 选择时间的时候
      customList: [], // 自定义coed
      deptObj: {},
      userObj: {},
      showSelectPicker: false,
      selectObj: {},
      requestList: [], // 附件必填列表
      getProductList,
    }
  },
  async created() {
    this.getAllOrder()
    await this.getDeptList()
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.detail = true
      await this.getUserList()
      this.getDetail()
    }
  },
  methods: {
    getAllOrder() {
      this.$toast.loading()
      getAllOrder()
        .then((res) => {
          // console.log(602, res)
          this.orderList = res.data
          this.customList = []
          this.orderList.forEach((item) => {
            item.expand = true
            if (item.properties) {
              item.properties.forEach((obj) => {
                if (obj.fixed === 0) {
                  let obj2 = { id: obj.id, code: obj.code }
                  this.customList.push(obj2)
                }
                // 如果是附件且必填情况
                if (obj.type === 7 && obj.required === 1) {
                  let objOrder = { name: obj.name, code: obj.code }
                  this.requestList.push(objOrder)
                }
              })
            }
          })
        })
        .finally(() => {
          this.$toast.clear()
        })
    },
    getDetail() {
      this.$toast.loading()
      getOrderDetail(this.id)
        .then((res) => {
          let obj = {}
          this.detailList = res.data
          res.data.forEach((item) => {
            if (item.properties) {
              item.properties.forEach((item2) => {
                obj[item2.code] = item2.actualValue
                // 选择部门
                if (item2.type === 4) {
                  obj[item2.id] = this.dealDeptName(item2.actualValue)
                  obj[item2.code] = item2.actualValue
                }
                // 选择员工
                else if (item2.type === 5) {
                  obj[item2.id] = this.dealUserName(item2.actualValue)
                  obj[item2.code] = item2.actualValue
                }
                // 多选项
                else if (item2.type === 2 && item2.multipleChoice === 1) {
                  obj[item2.code] = item2.actualValue ? item2.actualValue.split(',') : []
                }
                // 附件
                else if (item2.type === 7 && item2.code !== 'productUrl') {
                  if (item2.more) {
                    // 多个
                    let urlObj = {}
                    let list = item2.actualValue ? item2.actualValue.split(',') : []
                    let list2 = []
                    list.forEach((url) => {
                      urlObj = { name: url, url }
                      list2.push(urlObj)
                    })
                    obj[item2.code] = list2
                  } else {
                    // 单个
                    obj[item2.code] = item2.actualValue
                  }
                }
              })
            }
          })
          this.form = obj
          console.log(625, this.form)
        })
        .finally(() => {
          this.$toast.clear()
        })
    },

    confirmDate() {
      this.form[this.dataObj.code] = dateFormat(this.currentDate, 'yyyy-MM-dd hh:mm:ss')
      this.dateShow = false
    },
    dealDetailUrl(data) {
      let list = []
      if (data instanceof Array) {
        list = data.map((item) => item.url)
      } else {
        list.push(data)
      }
      return list
    },

    showProduct() {
      this.productShow = true
    },
    productSubmit() {
      if (this.selectProduct.id) {
        this.productShow = false
        this.form.productName = this.selectProduct.productSn
        this.form.productUrl = this.selectProduct.picture
        this.form.productUnitPrice = this.selectProduct.price
      } else {
        this.$toast.fail('请选择商品')
      }
    },

    clickUser(item) {
      this.userObj = item
      let deptId = undefined
      if (item.code === 'userId') {
        deptId = this.form.deptId
        if (!deptId) {
          this.$toast.fail('请先选择部门！')
          return
        }
      }
      this.$toast.loading()
      this.getUserList({ pageNum: 1, pageSize: 999, deptId })
        .then(() => {
          this.showPicker = true
        })
        .finally(() => {
          this.$toast.clear()
        })
    },
    async getUserList(obj) {
      return await getUserList(obj).then((res) => {
        this.userList = res.rows
      })
    },

    async getDeptList() {
      ;(this.options && this.options.length) ||
        (await getDeptList().then((res) => {
          this.options = res.data
          this.options.forEach((item) => {
            if (!item.children.length) {
              delete item.children
            }
          })
        }))
    },
    selectDept({ selectedOptions }) {
      this.showDepte = false
      this.form[this.deptObj.id] = selectedOptions.map((option) => option.deptName).join('/')
    },

    // 根据id获取部门名称
    dealDeptName(id) {
      // this.getDeptList()
      let deptName = ''
      this.options.forEach((item) => {
        if (item.deptId == id) {
          // console.log(item.deptName)
          deptName = item.deptName
          return
        }
      })
      return deptName
    },
    // 根据id获取员工名称
    dealUserName(id) {
      let userName = ''
      this.userList.forEach((item) => {
        if (item.userId === id) {
          userName = item.userName
          return
        }
      })
      return userName
    },

    cancelBack() {
      this.$router.go(-1)
    },
    onSubmit() {
      let form = JSON.parse(JSON.stringify(this.form))
      let customs = []
      for (let key in form) {
        let val = form[key]
        if (val instanceof Array) {
          if (val[0] && val[0].url) {
            form[key] = val.map((item) => item.url).join(',')
          } else {
            form[key] += ''
          }
        }
        this.customList &&
          this.customList.some((item) => {
            if (item.code === key) {
              customs.push({ id: item.id, value: form[key] })
              delete form[key]
              return true
            }
          })
      }
      form.customs = customs
      form.id = this.id
      form.externalUserid = this.$route.query.externalUserId
      this.$toast.loading()
      console.log('getOrderAdd', form)
      ;(this.id ? getOrderEdit : getOrderAdd)(form)
        .then((res) => {
          this.$router.go(-1)
        })
        .finally(() => {
          this.$toast.clear()
        })
    },
  },
}
</script>

<style lang="less" scoped>
.product-url {
  width: 120px;
  height: 120px;
  border: 1px dashed #666;
  line-height: 120px;
  text-align: center;
  color: #666;
}
.van-form {
  margin-bottom: 70px;
}
.cancat-btn {
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 15px 0;
  width: 100vw;
  display: flex;
  justify-content: space-evenly;
  border-top: 1px solid #f8f8f8;
}
.van-button {
  width: 28%;
  height: 30px;
  line-height: 30px;
}
.card {
  background: #ffffff;
  box-shadow: 0px 2px 6px -3px rgba(0, 0, 0, 0.04);
  border-radius: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  .title {
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    padding: 10px;
  }
}

.product-title {
  display: flex;
  justify-content: space-between;
  margin: 20px 10px;
  .title {
    font-size: 16px;
  }
}
.product-item {
  display: flex;
  padding: 10px;
  margin-bottom: 10px;
  .content {
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 70%;
    .describe {
      font-size: 14px;
      color: #4e5969;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .price {
      font-size: 14px;
      color: #f53f3f;
    }
  }
}
.active {
  background-color: @colorSub;
}

::v-deep {
  .van-dropdown-menu__title {
    padding-left: 0;
  }
  .van-dropdown-menu__bar {
    height: auto;
    box-shadow: none;
  }
  .van-checkbox-group--horizontal {
    gap: 20px;
  }
  .van-checkbox--horizontal {
    margin: 0;
  }
}
</style>
